package com.xlh.openai.controller;

import cn.hutool.db.sql.Order;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.xlh.openai.common.Result;
import com.xlh.openai.entity.ProductEntity;
import com.xlh.openai.exception.ServiceException;
import com.xlh.openai.service.OrderService;
import com.xlh.openai.service.ProductService;
import com.xlh.openai.service.impl.OpenAiChatServiceImpl;
import com.xlh.openai.vo.MallOrderCreateVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags = "商城controller")
@RestController
@RequestMapping("mall")
public class MallController {

    @Autowired
    private ProductService productService;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private OrderService orderService;


    @ApiOperation("商品列表")
    @RequestMapping(path = "/list",method = RequestMethod.GET)
    public Result<List<ProductEntity>> list(){
        List<ProductEntity> list = productService.list();
        return Result.success(list);
    }

    @ApiOperation("支付商品")
    @RequestMapping(path = "/pay",method = RequestMethod.GET)
    public Result<MallOrderCreateVO> pay(Integer mallId, HttpServletRequest request, HttpSession session){

        if(mallId == null){
            throw new ServiceException("商品ID不能为空！");
        }
        MallOrderCreateVO mallOrderCreateVO = productService.pay(mallId,request,session);
        return Result.success(mallOrderCreateVO);
    }

    @ApiOperation(value = "支付回调通知处理")
    @PostMapping("/notify")
    public String notify(@RequestBody String xmlData) throws WxPayException {
        try {
            final WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
            if (StringUtils.isNotBlank(notifyResult.getOutTradeNo())){
                orderService.paySuccessByNumber(notifyResult.getOutTradeNo());
            }
            return WxPayNotifyResponse.success("成功");
        } catch (Exception e) {
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }


}